package com.nativetalk.service.three.member.update;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeList;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberInvite;
import com.nativetalk.bean.send.TwNtSendHisInsert;
import com.nativetalk.bean.sms.Sms;
import com.nativetalk.bean.website.TsNtWebSiteConfIndex;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.*;
import com.nativetalk.dao.TdNtMembFoundChangeDao;
import com.nativetalk.dao.TdNtMemberDao;
import com.nativetalk.dao.TwNtSendHisDao;
import com.nativetalk.service.member.register.MemberRegisterService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizhun on 16/6/21.
 */
@Service
public class ThreeMemberUpdateServiceImpl implements  ThreeMemberUpdateService{
    private static Logger logger = Logger.getLogger(ThreeMemberUpdateServiceImpl.class);
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TwNtSendHisDao twNtSendHisDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private MemberRegisterService memberRegisterService;

    @Override
    public RetInfo updateMmeberPhone(TdNtMember tdNtMember,String code) {
        String logInfo = this.getClass().getName() + ":updateMmeberPhone:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtMember member = tdNtMemberDao.findTdNtMemberByPhone(tdNtMember.getMemb_phone());
            if (member != null){
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("该手机号已经注册,请更换手机号");
            } else {
                /**
                 * 判断验证码是否正确
                 *
                 */
                String key = "binding" + tdNtMember.getMemb_phone();
                Object code_obj = MemcachedUtils.get(key);
                logger.info("绑定手机号，缓存中的验证码key=" + key + ",value=" + code_obj);
                if (code_obj != null && code.equals(code_obj.toString())) {
                    tdNtMemberDao.updateMemberPhone(tdNtMember);

                    // 分配助教
                    logger.info("分配助教 【绑定手机号时分配助教】----------");
                    memberRegisterService.allotAssistant(tdNtMember.getMemb_id());
                    MemcachedUtils.replace(tdNtMember.getToken(), tdNtMember, 20 * 24 * 60 * 60);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("成功");
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("REGISTER.CODE.ERROR"));
                }
            }


        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateMmeberPhoneSendMessage(TdNtMember tdNtMember) {
        String logInfo = this.getClass().getName() + ":updateMmeberPhoneSendMessage:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            TdNtMember member = tdNtMemberDao.findTdNtMemberByPhone(tdNtMember.getMemb_phone());
            //验证手机号是否注册过
            if (member != null){
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("该手机号已经注册,请更换手机号");
                return retInfo;
            }

            Map<String, Integer> map = new HashMap<>();
            String dayKey = "day" + tdNtMember.getMemb_phone();//每天20条短信的限制的key day+手机号
            String register = "binding" + tdNtMember.getMemb_phone();
            String sencod = "sencod" + tdNtMember.getMemb_phone();

            //今天发送过短信
            Object o_day = MemcachedUtils.get(dayKey);
            int day_size = 0;
            //如果今天发送过短信，校验是否超过20条
            if (o_day != null) {
                map = (Map<String, Integer>) MemcachedUtils.get(dayKey);
                day_size = map.get("size");
                //今天短信是否超过20条
                if (day_size >= 20) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                    logger.info("发送短信超过20条" + tdNtMember.getMemb_phone());
                    return retInfo;
                }
            }

            //检查60秒是否发送过短信
            if ("0".equals(MemcachedUtils.get(sencod))) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                return retInfo;
            }

            String content = "您的验证码为CODE（5分钟内有效，如非本人操作请忽略）";
            String code = SmsCodeUtil.getSmsCode();
            content = content.replace("CODE", code);

            //将验证码放入缓存，验证码过期为5分钟
            logger.info(content);
            if (MemcachedUtils.get(register) == null) {
                MemcachedUtils.add(register, code, 5 * 60);
            } else {
                MemcachedUtils.replace(register, code, 5 * 60);
            }
            //在数据库中插入短信发送记录
            TwNtSendHisInsert twNtSendHis = new TwNtSendHisInsert();
            twNtSendHis.setPhoneno(tdNtMember.getMemb_phone());
            twNtSendHis.setYyyymmdd(CommonUtil.getMonth(now));
            twNtSendHis.setSms_provider_id(Integer.parseInt(code));

            //调用短信接口发送短信
            Sms sms = new Sms();
            sms.setMemb_phone_area(tdNtMember.getMemb_phone_area());
            sms.setMemb_phone(tdNtMember.getMemb_phone());
            boolean flag = SMSUtil.sendSms(sms, content);

            //发送成
            if (flag) {
                twNtSendHis.setSms_type("Y");
                twNtSendHisDao.insertTwNtSendHis(twNtSendHis);

                //短信发送成功，记录秒标记
                MemcachedUtils.add(sencod, "0", 60);
                //短信发送成功，日发送次数+1
                map.put("size", day_size + 1);
                MemcachedUtils.add(dayKey, map, 24 * 60 * 60);

                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip(ValidationMessages.getValue("MESSAGE.YES"));
                return retInfo;
            }
            //发送失败
            else {
                twNtSendHis.setSms_type("N");
                twNtSendHisDao.insertTwNtSendHis(twNtSendHis);
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("MESSAGE.NO"));
                return retInfo;
            }


        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
            return retInfo;
        }
    }

    @Override
    public @Transactional RetInfo memberBindingReward(TdNtMember tdNtMember) {
        String logInfo = this.getClass().getName() + ":memberBindingReward:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, Object> map  = new HashMap<>();
            map.put("memb_id",tdNtMember.getMemb_id());
            map.put("mfchg_change_name","注册奖励");
            TdNtMembFoundChangeList tdNtMembFoundChangeList = tdNtMembFoundChangeDao.findMemberByRegister(map);
            if (tdNtMembFoundChangeList == null) {
                /**
                 * 注册人添加资金变动记录
                 */

                Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
                BigDecimal binding = new BigDecimal(tsNtWebSiteConfIndexMap.get("27").getData_value());
                if (binding.compareTo(new BigDecimal(0)) == 0) {
                    BigDecimal memberBalance = tdNtMemberDao.findTdNtMemberBalabce(tdNtMember.getMemb_id());
                    TdNtMembFoundChangeInset tdNtMembFoundChangeInsetRegister = new TdNtMembFoundChangeInset();
                    tdNtMembFoundChangeInsetRegister.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMembFoundChangeInsetRegister.setMfchg_back_amount(memberBalance.add(binding));
                    tdNtMembFoundChangeInsetRegister.setMfchg_change_amount(binding);
                    tdNtMembFoundChangeInsetRegister.setMfchg_change_month(CommonUtil.getMonth(new Date()));
                    tdNtMembFoundChangeInsetRegister.setMfchg_change_name("注册奖励");
                    tdNtMembFoundChangeInsetRegister.setMfchg_change_type("1");
                    tdNtMembFoundChangeInsetRegister.setMfchg_front_amount(memberBalance);
                    tdNtMembFoundChangeInsetRegister.setState("2");
                    tdNtMembFoundChangeInsetRegister.setMfchg_number(CommonUtil.getOrderNub());
                    tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInsetRegister);
                    TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();
                    tdNtMemberInvite.setMemb_balance(tdNtMembFoundChangeInsetRegister.getMfchg_back_amount());
                    tdNtMemberInvite.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("领取成功!");
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip("活动已结束!");
                }
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("已领取!");
            }


        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public TdNtMembFoundChangeList findMemberByRegister(Map<String, Object> map) {
        return tdNtMembFoundChangeDao.findMemberByRegister(map);
    }
}
